package com.geeker.module.sys.user.sevice;

import cn.hutool.crypto.digest.DigestUtil;
import com.geeker.common.constant.RedisKeyPrefixConst;
import com.geeker.common.core.redis.RedisCache;
import com.geeker.common.exception.BusinessException;
import com.geeker.common.core.service.TokenService;
import com.geeker.module.sys.role.sevice.SysRoleService;
import com.geeker.common.core.domain.AccessUser;
import com.geeker.module.sys.user.domain.SysUser;
import com.geeker.module.sys.user.dto.LoginDto;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class AdminService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    public String login(LoginDto dto) {
        String username = dto.getUsername();
        SysUser user = sysUserService.getOne(QueryWrapper.create().eq(SysUser::getUserName, username));
        if(user == null)
            throw new BusinessException("登录用户：{} 不存在.", username);
        if(user.getStatus() == 0)
            throw new BusinessException("登录用户：{} 已被停用.", username);

        String retry_user = RedisKeyPrefixConst.PWD_ERR_CNT_KEY + username;
        Integer retryCount = redisCache.getCacheObject(retry_user);
        if (retryCount == null) {
            retryCount = 0;
        }
        if (retryCount >= maxRetryCount) {
            throw new BusinessException("密码输入错误{}次，帐户锁定{}分钟", maxRetryCount, lockTime);
        }

        //String password = SecureUtil.md5(dto.getPassword());
        String password = dto.getPassword();

        if(!DigestUtil.bcryptCheck(password, user.getPassword())){
            retryCount += 1;
            redisCache.setCacheObject(retry_user, retryCount, lockTime, TimeUnit.MINUTES);
            throw new BusinessException("账号或密码不正确!");
        }
        if (redisCache.hasKey(retry_user)) {
            redisCache.deleteObject(retry_user);
        }
        AccessUser accessUser = new AccessUser();
        accessUser.setUserId(user.getUserId())
                .setUserName(username)
                .setNickName(user.getNickName())
                .setDeptId(user.getDeptId())
                .setPermissions(sysRoleService.getMenuPermission(user));
        // 生成token
        return tokenService.createToken(accessUser);
    }

    public void logout() {
    }
}
